package com.hsmw.api.controller.forman;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hsmw.api.config.jwt.CurrentHsmwUserUtils;
import com.hsmw.api.config.jwt.LoginUser;
import com.hsmw.api.controller.pub.TencentPushUtils;
import com.hsmw.api.mapper.*;
import com.hsmw.api.service.*;
import com.hsmw.api.utils.NewGPSUtils;
import com.hsmw.api.utils.YLWUtils;
import com.hsmw.api.vo.*;
import com.hsmw.common.base.*;
import com.htn.common.core.base.BusinessType;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.*;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.*;
import com.hsmw.domain.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.htn.common.core.constant.CommonConstants.NO;
import static com.htn.common.core.constant.CommonConstants.ResponseStatus.*;

@Api(tags = "工长端相关接口表")
@RestController
@RequestMapping(value = "/api/htnapp")
public class HsmwHtnAppController extends BaseController<HsmwUserService, HsmwUser> {

    @Autowired
    private CurrentHsmwUserUtils currentHsmwUserUtils;


    @Autowired
    private HsmwOrderService  hsmwOrderService;
    @Autowired
    private HsmwDriverUserService  hsmwDriverUserService;

    @Autowired
    private HsmwOrderVehicleRequestService  hsmwOrderVehicleRequestService;

    @Autowired
    private HsmwConcretePlantInfoMapper hsmwConcretePlantInfoMapper;

    @Autowired
    private HsmwConcreteOperateRecordService hsmwConcreteOperateRecordService;

    @Autowired
    private HsmwConcreteInfoMapper hsmwConcreteInfoMapper;

    @Autowired
    private HsmwConcreteUserService hsmwConcreteUserService;

    @Autowired
    private HsmwConcretePlantInfoService hsmwConcretePlantInfoService;

    @Autowired
    private HsmwHtnUserService hsmwHtnUserService;

    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private HsmwUserDriverService hsmwUserDriverService;


    @Autowired
    private HsmwDispatchOrderRemarkService hsmwDispatchOrderRemarkService;


    @Autowired
    private HsmwDispatchOrderRemarkMapper hsmwDispatchOrderRemarkMapper;


    @Autowired
    private HsmwComplainService hsmwComplainService;

    @Autowired
    private HsmwOrderVehicleRelationService   hsmwOrderVehicleRelationService;

    @Autowired
    private HsmwHelpCenterMapper hsmwHelpCenterMapper;


    @Autowired
    private HsmwItemMapper  hsmwItemMapper;


    @Autowired
    private HsmwHelpCenterService  hsmwHelpCenterService;

    @Autowired
    private HsmwHelpAvaliableInfoMapper  hsmwHelpAvaliableInfoMapper;


    @Autowired
    private HsmwDriverNewsService hsmwDriverNewsService;


    @Autowired
    private HsmwSituationReportService hsmwSituationReportService;

    /**
     * 工长查询进行中，已完成，已取消的订单 以及司机
     */
    @Log(title = "搅拌站 查询 待接单， 已接单，已完成，已取消 的混凝土订单", businessType = BusinessType.QUERY)
    @ApiOperation(value = "工长查询进行中，已完成，已取消的订单", notes = "工长查询进行中，已完成，已取消的订单", produces = "application/json")
    @PostMapping("queryHtnConcreteOrder")
    public DataResponse foreManFindOrderStatusList(@RequestBody @Valid BasePage<HsmwOrder> basePage){
        String param = basePage.getQueryParam();
        IPage page = new Page(basePage.getPageNo(), basePage.getPageSize());
        HsmwHtnUser currentHtnHsmwUser =currentHsmwUserUtils.getCurrentHtnUserInfo();
        if(currentHtnHsmwUser == null){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"获取参数信息失败");
        }
        if(HtnUserTypeEnum.NORMAL.getValue().equals(currentHtnHsmwUser.getType())){
            return new DataResponse();
        }
        if(StringUtils.isBlank(param)){
            return new DataResponse(VALIDATE_FAILED,"查询的订单状态为空");
        }
        return new DataResponse(hsmwOrderService.selectConcreteOrderList(page,param,currentHtnHsmwUser.getOwnCompanyId(),null));
    }


    @Log(title = "搅拌站 查询 混凝土订单详情", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查询 混凝土订单详情", notes = "查询 混凝土订单详情", produces = "application/json")
    @PostMapping("queryHtnConcreteOrderDetail")
    public DataResponse queryHtnConcreteOrderDetail(String requestId){
        if(StringUtils.isBlank(requestId)){
            return new DataResponse(VALIDATE_FAILED,"查询的混凝土订单ID为空");
        }
        return new DataResponse(hsmwOrderService.selectConcreteOrderDetail(requestId));
    }




    /**
     * 工长将主订单置为完成（ 修改 ）
     * @param
     * @return
     */
    @Log(title = "结束混凝土订单 订单id：requestId 必输项目", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "结束混凝土订单 混凝土订单id：requestId 必输项目。", notes = " 工长将主订单置为完成", produces = "application/json")
    @PostMapping("/completeOrder")
    public DataResponse completeOrder(@RequestBody OrderQueryParam orderQueryParam) {
        try {
            HsmwHtnUser loginUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
            if(StringUtils.isBlank(orderQueryParam.getRequestId())){
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "混凝土订单ID不能为空，请重新输入！");
            }
            HsmwOrderVehicleRequest request = hsmwOrderVehicleRequestService.getById(orderQueryParam.getRequestId());
            request.setEndTime(LocalDateTime.now());
            request.setConcreteOrderStatus(ConcreteOrderStatusEnum.COMPLETED.getValue());
            hsmwOrderVehicleRequestService.updateById(request);
            //保存操作记录
            HsmwConcreteOperateRecord record = new HsmwConcreteOperateRecord();
            record.setOperUser(loginUser.getId());
            record.setOrderId(request.getOrderId());
            record.setRequestId(request.getId());
            record.setOperType(OperTypeEnum.ENDED.getValue());
            hsmwConcreteOperateRecordService.save(record);
            HsmwOrder orderInfos = hsmwOrderService.getById(request.getOrderId());

    //        if(!request.getConcretePlantId().equals(loginUser.getOwnCompanyId())){
                //发送混凝土发灰的云打印
                YLYNewOrderDTO newOrderDTO = new YLYNewOrderDTO();
                //获取搅拌站的 云打印机的 id
                HsmwConcretePlantInfo plantInfo = hsmwConcretePlantInfoMapper.selectById(request.getConcretePlantId());
                newOrderDTO.setMechineId(plantInfo.getMechineId());
                newOrderDTO.setItemName(orderInfos.getItemName());
                newOrderDTO.setOrderId(orderInfos.getId());
                newOrderDTO.setConstructionUnitName(orderInfos.getConstructionUnitName());
                newOrderDTO.setItemPosition(orderInfos.getItemPosition());
                DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
                newOrderDTO.setReachTime(dtf2.format(request.getReachTime()));
                newOrderDTO.setForemanName(orderInfos.getCreateName());
                HashMap param = new HashMap();
                param.put("orderId",orderInfos.getId());
                List<HsmwConcreteInfo> concreteInfos  = hsmwConcreteInfoMapper.selectConcretelist(param);
                newOrderDTO.setHsmwConcreteInfos(concreteInfos);
                newOrderDTO.setForemanName(orderInfos.getLinkmanName());
                newOrderDTO.setForemanTel(orderInfos.getLinkmanTelephone());
                newOrderDTO.setOperType(OperTypeEnum.ENDED.getValue());
                YLWUtils.sendStartOrPasuse(newOrderDTO);
                String msg = "您的混凝土订单已结束，请前往APP填写本次混凝土使用方量";
                List<HsmwHtnUser> users = hsmwHtnUserService.list(new LambdaQueryWrapper<HsmwHtnUser>()
                        .eq(HsmwHtnUser::getRoleType,HtnUserRoleEnum.LEADING.getValue())
                        .eq(HsmwHtnUser::getOwnCompanyId,request.getConcretePlantId())
                        .eq(HsmwHtnUser::getType,HtnUserTypeEnum.CONCRETE.getValue()));
                if (CollectionUtil.isNotEmpty(users)) {
                    HsmwHtnUser concreteUser = users.get(0);
                    if (StringUtils.isNotBlank(concreteUser.getUsername())) {
                        TencentPushUtils.pushForeManMsg(msg,concreteUser.getUsername(),"");
                        HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
                        hsmwDriverNews.setMessage(msg);
                        hsmwDriverNews.setUserId(concreteUser.getId());
                        hsmwDriverNews.setAlreadyRead(NO);
                        hsmwDriverNewsService.save(hsmwDriverNews);

                    }
                }
           // }

            return new DataResponse(SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"结束混凝土订单失败，请联系管理员！");
        }
    }

    /**
     * 下单人  取消混凝土订单
     * @param
     * @return
     */
    @Log(title = "下单人  取消混凝土订单 订单id：orderId 必输项目", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "取消混凝土订单 订单id：orderId 必输项目 status 0 是不取消， 1 是取消 泵车单。", notes = " 取消混凝土订单", produces = "application/json")
    @PostMapping("/cancleConcreteOrder")
    public DataResponse cancleConcreteOrder(String orderId,String cancelFlag) {
        try {
            if(StringUtils.isBlank(orderId)){
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "订单ID不能为空，请重新输入！");
            }
            if(StringUtils.isBlank(cancelFlag)){
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "是否取消泵车单不能为空，请重新输入！");
            }
            HsmwOrder hsmwOrder = hsmwOrderService.getById(orderId);
            if (StringUtils.isNull(hsmwOrder)){
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "该订单信息不存在，请重新输入！");
            }
            hsmwOrder.setOrderStatus(OrderStatusEnum.CANCELED.getValue());
            //订单创建人 取消的话 将 取消类型设置为 0
            hsmwOrder.setCancelType(CommonConstants.NO);
            hsmwOrder.setEndTime(LocalDateTime.now());
            boolean atc = hsmwOrderService.updateById(hsmwOrder);
            HsmwHtnUser user = hsmwHtnUserService.getById(hsmwOrder.getCreateUser());
            if(atc){
                String msg = "您的混凝土订单被"+hsmwOrder.getConcretePlantName()+"拒绝，订单已被取消!";
                //新增系统消息
                HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
                hsmwDriverNews.setUserId(user.getId());
                hsmwDriverNews.setMessage(msg);
                hsmwDriverNews.setAlreadyRead("0");
                hsmwDriverNewsService.save(hsmwDriverNews);
                //给工长推送信息 搅拌站拒绝接单的信息
               // TencentPushUtils.pushForeManMsg(msg,user.getUsername(),"foreman_refuse_phone");
                //TencentPushUtils.selfrunMsg(msg,user.getUsername(),"foreman_refuse_phone");
            }
            //如果是取消所有的泵车单 那么 取消下面所有的泵车单
            if(CommonConstants.YES.equals(cancelFlag)){
                OrderCancelVO orderCancelVO = new OrderCancelVO();
                orderCancelVO.setOrderId(orderId);
                orderCancelVO.setType(CommonConstants.YES);
                hsmwOrderService.cancelPumpOrder(orderCancelVO);
            }
            return new DataResponse();
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"工长将主订单置为完成失败，请联系管理员！");
        }
    }


    @ApiOperation(value = "确认接单",notes = "确认接单")
    @ApiImplicitParam(name = "requestId",value = "混天凝订单需求id",dataType = "String")
    @PostMapping("receiveConcreteOrderById")
    public DataResponse receiveConcreteOrderById(String requestId){
        return new DataResponse(hsmwConcretePlantInfoService.receiveConcreteOrderById(requestId));
    }



    @ApiOperation(value = "拒绝接单",notes = "拒绝接单")
    @ApiImplicitParam(name = "requestId",value = "混天凝订单需求id",dataType = "String")
    @PostMapping("refuseConcreteOrderById")
    public DataResponse refuseConcreteOrderById(String requestId){
        return new DataResponse(hsmwConcretePlantInfoService.refuseConcreteOrderById(requestId));
    }

    @ApiOperation(value = "搅拌站 取消混凝土订单",notes = "取消混凝土订单")
    @ApiImplicitParam(name = "requestId",value = "混天凝订单需求id",dataType = "String")
    @PostMapping("cancleConcreteOrderById")
    public DataResponse cancleConcreteOrderById(String requestId){
        return new DataResponse(hsmwConcretePlantInfoService.cancleConcreteOrderById(requestId));
    }


    /**
     * 下单人  取消混凝土订单
     * @param
     * @return
     */
    @Log(title = "搅拌站  取消混凝土订单 订单id：orderId 必输项目", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "搅拌站  取消混凝土订单  订单id：orderId 必输项目 ", notes = " 取消混凝土订单", produces = "application/json")
    @PostMapping("/concreteCancleOrder")
    public DataResponse concreteCancleOrder(String requestId,String cancelFlag) {
        try {
            if(StringUtils.isBlank(requestId)){
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "订单ID不能为空，请重新输入！");
            }
            HsmwOrder hsmwOrder = hsmwOrderService.getById(requestId);
            if (StringUtils.isNull(hsmwOrder)){
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "该订单信息不存在，请重新输入！");
            }
            hsmwOrder.setOrderStatus(OrderStatusEnum.CANCELED.getValue());
            //订单创建人 取消的话 将 取消类型设置为 0
            hsmwOrder.setCancelType(CommonConstants.YES);
            hsmwOrder.setEndTime(LocalDateTime.now());
            hsmwOrderService.updateById(hsmwOrder);
            return new DataResponse();
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"搅拌站  取消混凝土订单失败，请联系管理员！");
        }
    }


    @ApiOperation(value = "搅拌站确认方量",notes = "搅拌站确认方量")
    @PostMapping("updateConcreteVolume")
    public DataResponse updateConcreteVolume(@RequestBody QueryParamsVO queryParamsVO){
        if(queryParamsVO == null){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"参数信息错误");
        }
        hsmwConcretePlantInfoService.updateConcreteVolume(queryParamsVO);
        return new DataResponse(CommonConstants.ResponseStatus.SUCCESS,"操作成功");
    }

    @ApiOperation(value = "取消所有待打印的调用",notes = "取消所有待打印的调用")
    @PostMapping("cancelAllCall")
    public DataResponse cancelAllCall(){
       YLWUtils.cancelAllCall();
        return new DataResponse(CommonConstants.ResponseStatus.SUCCESS);
    }





    /**
     * 帮助中心列表
     */
    @ApiOperation(value = "项目端 帮助中心列表", notes = "帮助中心列表", produces = "application/json")
    @PostMapping("/findHelpCenterList")
    public DataResponse findHelpCenterList() {

        List<HsmwHelpCenter> data = hsmwUserDriverService.selectHelpInfoList();

        return new DataResponse(data);
    }




    /**
     * 帮助中心列表
     */
    @ApiOperation(value = "项目端 帮助信息 top 6", notes = "帮助中心列表", produces = "application/json")
    @PostMapping("/findTopHelpCenterList")
    public DataResponse findTopHelpCenterList() {

        List<HsmwHelpCenter> data = hsmwUserDriverService.selectTopHelpInfoList();

        return new DataResponse(data);
    }

    /**
     * 司机点击有用 没有按钮
     *
     * @param
     * @return
     */
    @ApiOperation(value = "修改帮助中心", notes = "修改帮助中心", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "帮助id", dataType = "String", required = true),
            @ApiImplicitParam(name = "params", value = "有用没用参数1 有用 2 没用  3 点击详情的时候 记录 查看次数", dataType = "String", required = false)
    })
    @PostMapping("/getHelpInfoDetail")
    public DataResponse getHelpInfoDetail(String id) {
        HsmwHelpCenter center = hsmwHelpCenterMapper.selectById(id);
        LoginUser currentUser = currentHsmwUserUtils.getCurrentUserInfo();
        //查询该用户的有用没有用信息
        List<HsmwHelpAvaliableInfo> infos = hsmwHelpAvaliableInfoMapper.selectList(new LambdaQueryWrapper<HsmwHelpAvaliableInfo>()
                .eq(HsmwHelpAvaliableInfo::getHelpId,id)
                .eq(HsmwHelpAvaliableInfo::getUserId,currentUser.getId()));
        if(CollectionUtil.isNotEmpty(infos)){
            HsmwHelpAvaliableInfo info = infos.get(0);
            center.setAvailiableFlag(info.getAvailableFlag());
        }
        return new DataResponse(center);
    }


    /**
     * 司机点击有用 没有按钮
     *
     * @param
     * @return
     */
    @ApiOperation(value = "修改帮助中心", notes = "修改帮助中心", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "帮助id", dataType = "String", required = true),
            @ApiImplicitParam(name = "params", value = "有用没用参数1 有用 2 没用  3 点击详情的时候 记录 查看次数", dataType = "String", required = false)
    })
    @PostMapping("/updateHelpCenterNum")
    public DataResponse updateHelpCenterNum(String id, String params) {
        return hsmwHelpCenterService.updateHelpCenterNum(id, params);
    }




    /**
     * 司机点击有用 没有按钮
     *
     * @param
     * @return
     */
    @ApiOperation(value = "新增 调度备注", notes = "新增 调度备注", produces = "application/json")
    @PostMapping("/addOrUpdateDispatchRemark")
    public DataResponse addOrUpdateDispatchRemark(@RequestBody DispatchOrderRemarkVO vo) {
        return hsmwDispatchOrderRemarkService.addOrUpdateDispatchRemark(vo);
    }



    /**
     * 创建或修改订单 查询常用的备注
     *
     * @param
     * @return
     */
    @Log(title = "查询常用的调度备注", businessType = BusinessType.INSERT)
    @ApiOperation(value = "查询常用的调度备注", notes = "查询常用的调度备注", produces = "application/json")
    @PostMapping("/getRecentDispatchRemark")
    public DataResponse getRecentDispatchRemark() {
        try {
            LoginUser currentUser = currentHsmwUserUtils.getCurrentUserInfo();
            HashMap param = new HashMap();
            param.put("userId",currentUser.getId());
            List<HsmwDispatchOrderRemark > orderRemarks =hsmwDispatchOrderRemarkMapper.selectRemarkList(param);
            if(CollectionUtil.isEmpty(orderRemarks)){
                orderRemarks= new ArrayList<>();
            }
            return new DataResponse(orderRemarks);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"创建或修改订单 查询常用的备注失败，请联系管理员！");
        }
    }



    @ApiOperation(value = "查看投诉信息的分页",notes = "查看投诉信息的分页",produces = "application/json")
    @PostMapping("/findComplainList")
    public DataResponse findComplainList(@RequestBody @Valid BasePage<HsmwComplain> basePage){

        return new DataResponse(hsmwComplainService.queryComplainList(basePage));
    }


    @ApiOperation(value = "对于投诉结果评价",notes = "对于投诉结果评价",produces = "application/json")
    @PostMapping("/updateComplainInfo")
    public DataResponse updateComplainInfo(@RequestBody @Valid HsmwComplain complain){

        return new DataResponse(hsmwComplainService.updateById(complain));
    }


    /**
     * "待接单列表 查询其他可用的车辆
     */
    @Log(title = "待接单列表 查询其他可用的车辆", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查询其他可用的车辆", notes = "查询其他可用的车辆", produces = "application/json")
    @PostMapping("/findVehicleCountAndDistance")
    public DataResponse findVehicleCountAndDistance(String requestId) {
        if(StringUtils.isBlank(requestId)){
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "订单需求ID不能为空，请重新输入！");
        }
        return  hsmwOrderService.findIdleVehicleCountAndDistance(requestId);
    }


    /**
     *待接单列表 替换其他可用的车辆
     */
    @Log(title = "待接单列表 替换其他可用的车辆", businessType = BusinessType.QUERY)
    @ApiOperation(value = "替换其他可用的车辆", notes = "查询其他可用的车辆", produces = "application/json")
    @PostMapping("/replaceOtherVehicle")
    public DataResponse replaceOtherVehicle(@RequestBody @Valid ReplaceVehicleVO vo) {
        if(StringUtils.isBlank(vo.getRequestId())){
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "订单需求ID不能为空，请重新输入！");
        }
        return  hsmwOrderService.replaceOtherVehicle(vo);
    }


    /**
     *待接单列表 替换其他可用的车辆
     */
    @Log(title = "查询子订单的状态", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查询子订单的状态", notes = "查询子订单的状态", produces = "application/json")
    @PostMapping("/queryPumpOrderStatus")
    public DataResponse queryPumpOrderStatus(String relationId) {
        if(StringUtils.isBlank(relationId)){
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "子订单ID不能为空，请重新输入！");
        }
        HsmwOrderVehicleRelation relation = hsmwOrderVehicleRelationService.getById(relationId);
        HashMap res= new HashMap();
        if(StringUtils.isNotNull(relation)){
            res.put("orderStatus",relation.getOrderStatus());
        }
        return  new DataResponse(res);
    }


    /**
     *查询通讯录
     */
    @Log(title = "查询通讯录 ", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查询通讯录", notes = "查询通讯录", produces = "application/json")
    @PostMapping("/queryAddressList")
    public DataResponse queryAddressList() {
        HsmwHtnUser currentHtnUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
        List<DriverAddressInfo> info = new ArrayList<>();
        if(HtnUserTypeEnum.CONCRETE.getValue().equals(currentHtnUser.getType()) || HtnUserTypeEnum.COMPANY.getValue().equals(currentHtnUser.getType())){
            HashMap param = new HashMap();
            param.put("ownCompanyId",currentHtnUser.getOwnCompanyId());
            param.put("userId",currentHtnUser.getId());
            info = hsmwHtnUserService.queryAddressList(param);
        }
        return  new DataResponse(info);
    }

    /**
     *查询通讯录
     */
    @Log(title = "查询通讯录 ", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查询通讯录", notes = "查询通讯录", produces = "application/json")
    @PostMapping("/destory")
    public DataResponse destory(String id) {
        hsmwOrderService.destoryGroup("HTN2022012911T8zn4568");
        return  new DataResponse();
    }

    /**
     *查询通讯录
     */
    @Log(title = "移除聊天用户 ", businessType = BusinessType.QUERY)
    @ApiOperation(value = "移除聊天用户", notes = "移除聊天用户", produces = "application/json")
    @PostMapping("/removeIMUser")
    public DataResponse removeIMUser(String  userId) {

        hsmwOrderService.removeAccount(userId);

        return  new DataResponse();
    }


    /**
     *查询通讯录
     */
    @Log(title = "公司用户或者搅拌站用户查询常用的施工单位 ", businessType = BusinessType.QUERY)
    @ApiOperation(value = "公司用户或者搅拌站用户查询常用的施工单位", notes = "公司用户或者搅拌站用户查询常用的施工单位", produces = "application/json")
    @PostMapping("/querAllConstructions")
    public DataResponse querAllConstructions() {
        List<String> allConstructions=new ArrayList<>();
        HsmwHtnUser currentHtnUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
        if(StringUtils.isNotNull(currentHtnUser.getType()) && (HtnUserTypeEnum.CONCRETE.getValue().equals(currentHtnUser.getType()) ||HtnUserTypeEnum.COMPANY.getValue().equals(currentHtnUser.getType()))){
            HashMap param = new HashMap();
            param.put("ownCompanyId",currentHtnUser.getOwnCompanyId());
            allConstructions =hsmwItemMapper.querAllConstructions(param);
        }
        return  new DataResponse(allConstructions);
    }


    /**
     *查询通讯录
     */
    @Log(title = "GPS设备看视频获取token ", businessType = BusinessType.QUERY)
    @ApiOperation(value = "GPS设备看视频获取token", notes = "GPS设备看视频获取token", produces = "application/json")
    @PostMapping("/getGpsToken")
    public DataResponse getGpsToken() {
        return  new DataResponse(NewGPSUtils.getAccessToken());
    }




    /**
     *查询通讯录
     */
    @Log(title = "同意或者拒绝 位置纠错信息 ", businessType = BusinessType.QUERY)
    @ApiOperation(value = "同意或者拒绝 位置纠错信息 id : 纠错信息id， flag : 1 是同意 2:不同意", notes = "同意或者拒绝 位置纠错信息", produces = "application/json")
    @PostMapping("/receiveOrRefuseLocation")
    public DataResponse receiveOrRefuseLocation(String id, String flag) {
        HsmwSituationReport report = hsmwSituationReportService.getById(id);
        if(null== report){
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "您输入的纠错信息id，请重新输入！");
        }
        String msg = "";
        HsmwDriverUser user =hsmwDriverUserService.getById(report.getUserId());
        if(flag.equals(CommonConstants.YES)){
            report.setStatus(flag);
            hsmwSituationReportService.updateById(report);
            //同时 修改 订单的项目位置信息
            HsmwOrder order = hsmwOrderService.getById(report.getOrderId());
         /*   order.setLat(report.getLat());
            order.setLng(report.getLng());
            order.setItemPosition(report.getAddress());
            hsmwOrderService.updateById(order);*/
            HsmwItem item = hsmwItemMapper.selectById(order.getItemId());
            item.setLat(report.getLat());
            item.setLng(report.getLng());
            item.setPositionDetail(report.getAddress());
            hsmwItemMapper.updateById(item);
            //更新 所有未到达的订单的位置信息
            HashMap param = new HashMap();
            param.put("itemId",order.getItemId());
            param.put("lng",report.getLng());
            param.put("lat",report.getLat());
            param.put("itemPosition",report.getAddress());
            hsmwItemMapper.updateItemInfoOfOrders(param);


            msg = "您的位置纠错申请已通过，请查看最新项目位置";
            //同时 给司机推送信息
            WebSocketReturnVO webSocketReturnVO = new WebSocketReturnVO();
            webSocketReturnVO.setOrderId(report.getOrderId());
            webSocketReturnVO.setMessage(msg);
            TencentPushUtils.htnPushDriverMsg(msg,user.getUsername(),webSocketReturnVO);
            HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
            hsmwDriverNews.setMessage(msg);
            hsmwDriverNews.setUserId(user.getId());
            hsmwDriverNews.setAlreadyRead(NO);
            hsmwDriverNewsService.save(hsmwDriverNews);

        }else {
            report.setStatus(flag);
            hsmwSituationReportService.updateById(report);
            msg ="您的位置纠错已被驳回，有问题请及时与调度联系";
            //同时 给司机推送信息
            WebSocketReturnVO webSocketReturnVO = new WebSocketReturnVO();
            webSocketReturnVO.setOrderId(report.getOrderId());
            webSocketReturnVO.setMessage(msg);
            TencentPushUtils.htnPushDriverMsg(msg,user.getUsername(),webSocketReturnVO);

            HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
            hsmwDriverNews.setMessage(msg);
            hsmwDriverNews.setUserId(user.getId());
            hsmwDriverNews.setAlreadyRead(NO);
            hsmwDriverNewsService.save(hsmwDriverNews);
        }
        return  new DataResponse();
    }

    /**
     *查询通讯录
     */
    @Log(title = "查询位置纠错信息 ", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查询位置纠错信息", notes = "查询位置纠错信息", produces = "application/json")
    @PostMapping("/querSituationReportInfo")
    public DataResponse querSituationReportInfo(String relationId) {
        List<HsmwSituationReport> reports =hsmwSituationReportService.list(new LambdaQueryWrapper<HsmwSituationReport>()
                .eq(HsmwSituationReport::getRelationId,relationId)
                .eq(HsmwSituationReport::getStatus, NO));
        return  new DataResponse(reports);
    }


}
